import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateMainlyCategoryDto, DeleteMainlyCategoryDto, EditMainlyCategoryDto, FindUserAllDto } from './dto/mainly-category.dto';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class MainlyCategoryService {
  constructor(
    private readonly prismaService: PrismaService,
  ) { }

  /**
   * 创建主页分类
   * @param cmcd 创建主页分类数据传输对象
   * @returns 成功或失败消息
   */
  async create(cmcd: CreateMainlyCategoryDto) {
    // 检查类别是否已存在
    const findOne = await this.prismaService.mainlyCategory.findFirst({
      where: { name: cmcd.name, userId: cmcd.userId }
    })
    if (findOne) {
      throw new HttpException('类别已存在', HttpStatus.BAD_REQUEST)
    }
    try {
      await this.prismaService.mainlyCategory.create({ data: { ...cmcd } })
      return "类别添加成功"
    } catch (error) {
      throw new HttpException('类别添加失败', HttpStatus.BAD_REQUEST)
    }
  }

  async edit(emcd: EditMainlyCategoryDto) {
    try {
      await this.prismaService.mainlyCategory.update({ where: { id: emcd.id }, data: { ...emcd } })
      return "类别编辑成功"
    } catch (error) {
      throw new HttpException('类别编辑失败', HttpStatus.BAD_REQUEST)
    }
  }

  async delete(dmcd: DeleteMainlyCategoryDto) {
    // 判断是否有child
    const hasChild = await this.prismaService.mainlyCategory.findUnique({
      where: { id: dmcd.id },
      include: {
        _count: { select: { children: true } } // 仅计数不返回数据
      }
    });
    if ((hasChild?._count?.children ?? 0) > 0) {
      throw new HttpException('类别删除失败,该类别下存在子类别', HttpStatus.BAD_REQUEST)
    }

    const hasSubCat = await this.prismaService.mainlyCategory.findUnique({
      where: { id: dmcd.id },
      include: {
        _count: { select: { subCategory: true } } // 仅计数不返回数据
      }
    });
    if ((hasSubCat?._count?.subCategory ?? 0) > 0) {
      throw new HttpException('类别删除失败,该类别下存在子类别', HttpStatus.BAD_REQUEST)
    }
    try {
      await this.prismaService.mainlyCategory.delete({ where: { id: dmcd.id } })
      return "类别删除成功"
    } catch (error) {
      throw new HttpException('类别删除失败', HttpStatus.BAD_REQUEST)
    }
  }

  async findUserAll(fuad: FindUserAllDto) {
    try {
      const res = await this.prismaService.mainlyCategory.findMany({
        where: { userId: fuad.userId, level: fuad.level, isDelete: false },
      });
      return res
    } catch (error) {
      throw new HttpException('类别查找失败', HttpStatus.BAD_REQUEST)
    }
  }
}
